package com.qf.controller;

import com.github.pagehelper.Constant;
import com.github.pagehelper.PageInfo;
import com.qf.constant.SsmConstant;
import com.qf.entity.Item;
import com.qf.enums.ExceptionInfoEnum;
import com.qf.exception.SsmException;
import com.qf.service.ItemService;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.IOUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@Controller
@Slf4j
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${pic.maxSize}")
    private Long picMaxSize;

    @Value("${pic.types}")
    private String types;
    //跳转到商品列表
    @GetMapping("/item-list")
    public String itemList( String name,
                           @RequestParam(defaultValue = "1")Integer page,
                           @RequestParam(defaultValue = "5")Integer size,
                           Model model){
        PageInfo<Item> pageInfo = itemService.list(name,page, size);
        model.addAttribute("name",name);
        model.addAttribute("pageInfo",pageInfo);
        return "/item/item_list";
    }
    //跳转到添加商品页面
    @GetMapping("/add-ui")
    public String addItem(){
        return "/item/item_add";
    }

    //添加商品
    @PostMapping("/add")
    @ResponseBody
    public ResultVO save(MultipartFile picFile, @Valid Item item, BindingResult bindingResult, HttpServletRequest req) throws IOException {
//        3. 在controller的方法参数上使用MultipartFile对象接收文件上传项.
//        4. 接收普通表单项Item item,并校验.
//        5. 文件上传项.是否为空
        if(picFile==null||picFile.getSize()==0){
            log.info("【添加商品】商品图片为必填项，岂能为空");
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(),"商品图片为必填项，岂能为空");
        }
//        5.1 大小判断.
        if(picFile.getSize()>picMaxSize){
            log.info("【添加商品】商品图片过大，size={}",picFile.getSize());
            throw new SsmException(ExceptionInfoEnum.PIC_GREATER);
        }
//        5.2 类型判断.
        List<String> typeList = Arrays.asList(types.split(","));
        String fileName=picFile.getOriginalFilename();
        String typeName=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(!typeList.contains(typeName)){
            log.info("【添加商品】图片类型不正确，typeName={}",typeName);
            throw new SsmException(ExceptionInfoEnum.PIC_NAMETYPE_ERROR);
        }
//        5.3 是否损坏.
        BufferedImage img = ImageIO.read(picFile.getInputStream());
        if(img==null){
            log.info("【添加商品】图片已损坏，picFile={}",picFile);
            throw new SsmException(ExceptionInfoEnum.PIC_BREAK);
        }
//        5.4 新名字.
        String newName = UUID.randomUUID().toString()+"."+typeName;
        String path= req.getServletContext().getRealPath("/")+"static/images/"+newName;
        File file = new File(path);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
//        5.5 保存到本地
        IOUtils.copy(picFile.getInputStream(),new FileOutputStream(file));
//        5.6 将图片的访问路径设置到item对象中.
        String pic =req.getContextPath()+"/static/images/"+newName;
        item.setPic(pic);
//        6. 校验普通表单项.
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【添加商品】参数不合法，msg={}",msg);
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(),msg);
        }
//        7. 调用serivce保存.
        itemService.save(item);
//        8. 响应数据.
        return new ResultVO(0,"成功",null);
    }

    //删除商品
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public ResultVO deleteById(@PathVariable Integer id){
        itemService.deleteById(id);
        return new ResultVO(0,"成功",null);
    }


    //跳转到修改商品页面
    @GetMapping("/update-ui")
    public String updateUI(Integer id,Model model){
        Item item = itemService.findItemById(id);
        model.addAttribute("item",item);
        return "/item/item_update";
    }

    //修改商品信息
    @PostMapping("/update")
    @ResponseBody
    public ResultVO update(MultipartFile picFile,@Valid Item item,BindingResult bindingResult,HttpServletRequest req) throws IOException {
        //1.文件上传是否为空
        if(picFile.getSize()==0||picFile==null){
            log.info("【修改商品】图片为必填项，岂能为空");
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(),"图片为必填项岂能为空");
        }
        //2.图片大小判断
       if(picFile.getSize()>picMaxSize){
           log.info("【修改商品】图片过大，picSize={}",picFile.getSize());
           throw new SsmException(ExceptionInfoEnum.PIC_GREATER);
       }
       //3.类型判断
        List<String> typeList = Arrays.asList(types.split(","));
        String fileName = picFile.getOriginalFilename();
        String typeName = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(!typeList.contains(typeName)){
            log.info("【修改商品】图片类型错误，typeName={}",typeName);
            throw new SsmException(ExceptionInfoEnum.PIC_NAMETYPE_ERROR);
        }
        //4.是否损坏
        BufferedImage img = ImageIO.read(picFile.getInputStream());
        if(img==null){
            log.info("【修改商品】图片已损坏，picFile={}",picFile);
            throw new SsmException(ExceptionInfoEnum.PIC_BREAK);
        }
        //5.新名字
        String newName = UUID.randomUUID().toString()+"."+typeName;
        //路径
        String path=req.getServletContext().getRealPath("/")+"static/images/"+newName;
        File file = new File(path);
        if(!file.exists()){
            file.getParentFile().mkdirs();
        }
        //6.保存到本地
        IOUtils.copy(picFile.getInputStream(),new FileOutputStream(path));
        //7将图片路径设置到item中
        String pic = req.getContextPath()+"/static/images/"+newName;
        item.setPic(pic);
        //8.校验用户表单
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【修改商品】参数不合法，msg={}",msg);
            throw new SsmException(ExceptionInfoEnum.PARAM_ERROR.getCode(),msg);
        }

        //9.调用service修改商品信息
        itemService.update(item);

        //10.响应会页面
        return new ResultVO(0,"成功",null);

    }


}
